import { mapGetters } from 'vuex';
import { getTopNavList } from '@/utils/auth'
import { getRoleDetailApi, getSysMenuTreeApi, updateRolePermissionsApi, getSysStructsTreeApi } from './permission-setting.service';
import { alertHtmlWithCallback, alertMessage, getTreeData, showAlertMessage } from '@/utils/utils';
import StructsTree from '@/business-components/structs-tree/structs-tree';
export default {
  name: 'create-user',
  components: { StructsTree },
  directives: {},
  props: {
    roleId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      file_url: process.env.VUE_APP_FILE_URL, // 头像url
      loading: false, // table loading
      showDialog: true, // 是否显示弹窗
      title: '职位权限设置',
      roleName: '', // 角色名称
      treeData: [],
      editForm: {}, // 编辑用户表单
      props: { // 级联选择器
        checkStrictly: true,
        label: 'name',
        value: 'objectId',
        emitPath: false
      },
      roles: [], // 角色列表
      activeNavName: '',
      topNavList: JSON.parse(getTopNavList()),
      structuresTreeData: [],
      defaultProps: { // 部门树变量
        children: "children",
        label: "name",
        value: 'objectId',
        multiple: true
      }
    }
  },
  computed: {
    ...mapGetters([
      'codesCheck'
    ])
  },
  created() {
    this.getRoleDetail();
    this.activeNavName = this.topNavList[0].objectId;
    this.getSysMenuTree();
    this.getSysStruct();
  },
  methods: {
    // 获取详情
    getRoleDetail() {
      getRoleDetailApi(this.roleId).then(res => {
        this.roleName = res.data.name;
      })
    },
    // 获取菜单树
    getSysMenuTree() {
      const postData = {
        roleId: this.roleId,
        applicationId: this.activeNavName
      }
      getSysMenuTreeApi(postData).then(res => {
        let dataTree = res.data; // 是一个树结构的数据
        const setTree = function(datas) {
          let checksP = 0; // 同层的code的选中数量
          let allChecksP = 0; // 同层的code所有数量
          for (let i = 0; i < datas.length; i++) {
            const item = datas[i];
            item.checkCount = 0; // 选中的个数
            if (item.pid !== '0') { // 不是第一层
              // item.dataChecks = [];
              allChecksP += item.permissions.length; // 把所有的code数量统计出来
              for (let j = 0; j < item.permissions.length; j++) {
                const permissionData = item.permissions[j];
                if (permissionData.checkFlag) {
                  item.checkCount += 1;
                  checksP += 1;
                  // item.dataChecks.push(permissionData.objectId)
                }
                if (i === datas.length - 1 && j === item.permissions.length - 1) {
                  item.checksP = checksP; // 把所有选中的数量统计出来
                  item.allChecksP = allChecksP; // 把所有的code数量统计出来
                  checksP = 0; // 清空数据
                  allChecksP = 0; // 清空数据
                }
              }
            }
            if (item.children && item.children.length) {
              setTree(item.children);
            }
          }
          return datas
        }
        dataTree = setTree(dataTree);
        for (let i = 0; i < dataTree.length; i++) {
          const item = dataTree[i];
          if (item.children && item.children.length) {
            item.checksP = item.children[item.children.length - 1].checksP;
            item.allChecksP = item.children[item.children.length - 1].allChecksP;
            item.checkAll = item.checksP === item.allChecksP;
            item.isIndeterminate = item.checksP > 0 && item.checksP < item.allChecksP;
          } else {
            item.checkAll = true
          }
        }
        this.treeData = dataTree
      })
    },

    // 获取部门列表
    getSysStruct() {
      this.loading = true;
      getSysStructsTreeApi().then(res => {
        this.loading = false;
        this.structuresTreeData = getTreeData(res.data);
      });
    },

    handleClick() {
      this.getSysMenuTree();
    },

    // 数据权限全选
    allDataChange() {
      let list = []
      if (this.editForm.isAllDataCheck) {
        list = this.setAllDataCheck(this.structuresTreeData)
      }
      this.recursionAllDataTree(this.treeData, list)
    },

    recursionAllDataTree(tree, list) {
      tree.forEach(element => {
        this.$set(element, 'roleStructPermissionIdsOfCascader', this.editForm.isAllDataCheck ? list : []);
        if (element.children) {
          this.recursionAllDataTree(element.children, list)
        }
      })
    },

    // 设置全选递归函数
    setAllDataCheck(tree, stack = [], pathList = []) {
      if (!tree) return
      for (let data of tree) {
        stack.push(data.objectId)
        if (data.children && data.children.length) {
          this.setAllDataCheck(data.children, stack, pathList)
        } else {
          pathList.push([...stack])
        }
        stack.pop(data.objectId)
      }
      return pathList
    },

    allOperationChange() {
      this.treeData.forEach(element => {
        this.$set(element, 'isIndeterminate', false)
        this.$set(element, 'checkAll', this.editForm.isAllOperationCheck);
        this.handleCheckAllChange(element)
      })
    },

    handleCheckAllChange(datas) { // 全选
      if (datas.children && datas.children.length) {
        let checksP = 0; // 同层的code的选中数量
        let allChecksP = 0; // 同层的code所有数量
        for (let i = 0; i < datas.children.length; i++) {
          let item = datas.children[i];
          allChecksP += item.checkCount; // 把所有的code数量统计出来
          if (datas.checkAll) {
            item.checkCount = item.permissions.length;
            checksP += item.checkCount; // 把所有选中的数量统计出来
          } else {
            item.checkCount = 0;
            checksP = 0; // 把所有选中的数量统计出来
          }
          // item.dataChecks = [];
          for (let j = 0; j < item.permissions.length; j++) {
            const permissionData = item.permissions[j];
            if (datas.checkAll) {
              permissionData.checkFlag = true;
              // item.dataChecks.push(permissionData.objectId)
            } else {
              permissionData.checkFlag = false;
            }
            if (i === datas.children.length - 1 && j === item.permissions.length - 1) {
              item.checksP = checksP; // 把所有选中的数量统计出来
              item.allChecksP = allChecksP; // 把所有的code数量统计出来
              checksP = 0; // 清空数据
              allChecksP = 0; // 清空数据
            }
          }
        }
        datas.checksP = datas.children[datas.children.length - 1].checksP;
        datas.allChecksP = datas.children[datas.children.length - 1].allChecksP;
        if (datas.checkAll) {
          datas.isIndeterminate = false;
        } else {
          datas.checkAll = false;
          datas.isIndeterminate = false;
        }
      }
      for (let i = 0; i < this.treeData.length; i++) {
        if (this.treeData[i].objectId === datas.objectId) {
          this.treeData[i] = datas;
        }
      }
      this.$forceUpdate();
    },

    handleCheckOneChange(row, checkFlag) { // 单选
      for (let i = 0; i < this.treeData.length; i++) {
        const data = this.treeData[i];
        if (data.objectId === row.pid) {
          if (checkFlag) {
            data.checksP += 1 // 父元素，选中的code + 1
          } else {
            data.checksP -= 1 // 父元素，选中的code - 1
          }
          if (data.checksP === data.allChecksP) { // 父元素所有子元素的所有的code 和 选中的code相等
            data.checkAll = true;
            data.isIndeterminate = false;
          } else if (data.checksP < 1) { // 父元素所有子元素code都没选中
            data.checkAll = false;
            data.isIndeterminate = false;
          } else { // 父元素部分子元素code选中
            data.checkAll = false;
            data.isIndeterminate = true;
          }
        }
      }
      this.$forceUpdate();
    },

    // 保存
    save() {
      const postData = JSON.parse(JSON.stringify(this.treeData));
      const arr = [];
      let _that = this;
      function postResult(postData) {
        for (let i = 0; i < postData.length; i++) {
          const item = postData[i];
          const dataChecks = item.permissions.map(item => {
            return {
              objectId: item.objectId,
              checkFlag: item.checkFlag
            }
          })
          const objectPost = {
            roleId: _that.roleId,
            menuCode: item.code,
            structIds: item.roleStructPermissionIdsOfCascader.reduce((pre, cur) => {
              return pre.concat(cur)
            }, []),
            dataChecks: item.pid !== '0' ? dataChecks : []
          }
          arr.push(objectPost)
          if (item.children && item.children.length) {
            postResult(item.children)
          }
        }
      }
      postResult(postData)
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          const message = {
            roleName: this.roleName
          }
          const alertMsg = showAlertMessage(`请确认角色信息`, message)
          alertHtmlWithCallback(alertMsg, `确认要配置该角色操作权限及数据权限吗？`).then(yes => {
            if (yes) {
              updateRolePermissionsApi(arr).then(res => {
                alertMessage(res.message);
                this.closeDialog();
                this.loading = false;
                this.$emit('reload', true);
              }).catch(() => {
                this.loading = false;
              })
            }
          })
        } else {
          return false;
        }
      });
    },

    // 关闭dialog时需要告诉父组件隐藏弹窗
    closeDialog() {
      this.showDialog = false;
      this.$emit('close', true);
    }
  }
}
